import os
import re
import pymongo
import configparser
import common.gyblog as log
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService

LOG = log.get_logger()
SERVICE = ChromeService(executable_path="../common/chromedriver.exe")
CONNECTION_STR = 'mongodb://192.168.0.196:27017/?readPreference=primary&appname=MongoDB%20Compass%20Community&ssl=false'

# 读取配置
cf = configparser.ConfigParser()
cf.read(os.path.dirname(os.path.abspath('.')) + '/download_javbook/config.ini')
DATA_BASE = cf.get('javbook', 'DATA_BASE')
DB_COL = cf.get('javbook', 'DB_COL')
SERIES = cf.get('javbook', 'SERIES')
YEAR = cf.get('javbook', 'YEAR')


def get_movies(url):
    # 创建 WebDriver 对象
    driver = webdriver.Chrome(service=SERVICE)
    # 导航到页面
    driver.get(url)
    # 使用 XPath 定位元素
    nums = driver.find_elements(By.XPATH,
                                '//*[@id="td-outer-wrap"]/div[2]/div/div[2]/div/div/div[position()]/div[position()]/div/h3/a')
    len_num = len(nums)
    print('抓取nums:{}，数量为{}个'.format(url, str(len_num)))
    LOG.info('抓取nums:{}，数量为{}个'.format(url, str(len_num)))
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]

    for n in nums:
        title = n.text
        try:

            num = re.search("\d{6}_\d{3}", title).group()
            # 查询
            query = {'series': SERIES, 'num': num}
            query_ans = list(db_col.find(query))
            if len(query_ans) == 1:
                print('搜索到{}，跳过'.format(num))
            if len(query_ans) > 1:
                print('搜索到多个！！：{}'.format(num))
            if len(query_ans) == 0:
                print('没有搜到{}，插入'.format(num))
                year = '20' + num[4:6]
                my_dict = {'num': num, 'series': SERIES, 'year': year, 'detail_url': '',
                           'tor': '', 'tor_name': '', 'is_download': '3xplanet', 'is_keep': 'N'}
                print(my_dict)
                LOG.info(str(my_dict))
                db_col.insert_one(my_dict)
        except:
            print(title)

    db_client.close()
    driver.close()

    return len_num


if __name__ == '__main__':
    url = 'https://3xplanet.net/page/{}/?s=1Pondo'

    for i in range(1, 41):
        while True:
            len_num = get_movies(url.format(str(i)))
            if len_num != 0:
                break
